package com.yuyuan.api.config;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuyuan.common.domain.dto.UserDTO;
import com.yuyuan.common.utils.UserHolder;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Author: kestrel
 * @Version:1.0
 * @Date: 2024/6/18
 */
@Component
public class DefaultFeignConfig {

    @Autowired
    private ObjectMapper objectMapper = new ObjectMapper();

    @Bean
    public Logger.Level fullFeignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public RequestInterceptor userInfoRequestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                UserDTO userDTO = UserHolder.getUser();
                if(userDTO != null){
                    String userDTOStringJSON = userDTO.toStringJSON();
                    String encodedUserDTOStringJSON;
                    try {
                        encodedUserDTOStringJSON = URLEncoder.encode(userDTOStringJSON, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                    template.header("user-info", encodedUserDTOStringJSON);
                }
            }
        };
    }

}

